<template>
	<!-- 处方上传 -->
	<view class="container">
		<cu-custom bgColor="bg-red" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">购买推荐处方</block>
		</cu-custom>
		<view class="thk-lc">
			<image src="../../../static/images/cflc.png"></image>
		</view>

		<view class="header radius shadow-warp">
			<view class="flex header-title justify-between">
				<view class="flex-twice pres-title">
					<text class>选择推荐处方</text>
				</view>
				<!-- <view class="text-center">
					<button class="cu-btn round bg-red">购买推荐处方</button>
				</view> -->

			</view>


			<view class="wrapper-list bg-white radius">
				<scroll-view class="scroll-view_x" scroll-x style="width:auto;overflow:hidden;">
					<view class="pres-image" v-if="displayShow">
						<view class="cuIcon-close cloes" @tap="showTipOpen"></view>
						<image :src="purchaseSpu.picUrls[0]" mode="scaleToFill"></image>
					</view>
					<view class="pres-image" @tap="upload">
						<image src="../../../static/images/camera.png"></image>
					</view>
				</scroll-view>
			</view>
		</view>
		<view class="main radius shadow-warp">
			<view class="cu-form-group text-right">
				<view class="title">用药人</view>
				<input placeholder="请输入用药人姓名" type="text" @input="setBuyname"></input>
			</view>
			<view class="cu-form-group text-right arrow">
				<view class="title">性别</view>
				<picker :range="genderList" @change="genderChange">
					<text class="picker">{{gender || '请选择'}}</text>
				</picker>
			</view>
			<view class="cu-form-group text-right">
				<view class="title">处方付数</view>
				<input placeholder="请输入处方付数" type="number" @input="selectNum" name="input"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">是否代煎</view>
				<switch :checked="djFlag" class="green" @change="isdj"></switch>
			</view>
			<!-- <view class="cu-form-group">
				<view class="title">颗粒剂处方</view>
				<switch :checked="tjtype === 1" class="green" @change="isklj"></switch>
			</view> -->
		</view>
		<view class="main radius shadow-warp">
			<view class="address-btn flex">
				<view v-for="(item, index) in distributionList" :key="index"
					:class="'btn-item flex-sub text-center ' + (transType == item.expressId ? 'btn-color' : '' )">
					<view @tap="btnClick(item)">
						{{item.name}}
					</view>
				</view>
			</view>
			<view class="line-address">
				<view class="cuIcon-location"></view>
				<view class="address" @tap="jumpToAddressList" v-if="userAddress.id != '' && transType != 0">
					<text class>{{userAddress.provinceName}}</text>
					<text class>{{userAddress.cityName}}</text>
					<text class>{{userAddress.countyName}}</text>
					<text v-if="userAddress.address">{{userAddress.address}}</text>
					<text class>{{userAddress.detailInfo}}</text>
					<text class>{{userAddress.userName}}</text>
					<text class>{{userAddress.telNum}}</text>
				</view>
				<view class="address" v-if="transType == 0">
					<!-- <picker :range="adddressList"><text >北京市西城区阜内大街165号（白塔寺药店二层饮片收银台）</text></picker> -->
					<text>北京市西城区阜内大街165号（白塔寺药店二层饮片收银台）</text>
				</view>
				<view class="addAddres" v-if="userAddress.id == '' && transType != 0" @tap="jumpToAddressList">
					请添加收货地址
				</view>
				<view class="cuIcon-right"></view>
			</view>
		</view>
		<view class="main">
			<navigator class="solid-bottom" hover-class="none" url="/pages/users/order-invoice/index">
				<view class="recipe solid-bottom">
					<view class="recipe_l">
						<view class="">发票</view>
					</view>
					<view v-if="!invoiceFlag" class="flex">
						<view style="margin-right: 10rpx;" class="">不需要开发票</view>
						<text class="cuIcon-right"></text>
					</view>
					<view v-if="invoiceFlag" style="margin-right: 10rpx;" class="flex">
						<view class="">{{invoiceData[0].rise}}</view>
						<view class="">{{invoiceData[0].tax == null?'':invoiceData[0].tax}}</view>
						<text class="cuIcon-right"></text>
					</view>
				</view>
			</navigator>
			<form>
				<view class="cu-form-group align-start">
					<view class="title">备注</view>
					<textarea maxlength="-1" @input="memoInput" :value="memo" placeholder="请输入您的备注信息"></textarea>
				</view>
			</form>
		</view>
		<view style="height:60px" class="safe"></view>
		<view class="bg-white padding-lr-sm flex flex-direction fixed safe">
			<button class="cu-btn bg-red margin-tb-sm lg" @tap="wxgetSnowflake" :loading="loading" :disabled="loading">
				提交
			</button>
		</view>
		<!-- 提示图片上传成功 -->
		<!-- <view :class="'cu-modal ' + (successTip? 'show' : '' )">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content text-black">提示</view>
					<view class="action" @tap="successTipHide">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-xl">您的处方已经上传成功,请等待审核！</view>
				<view class="cu-bar bg-white justify-end">
					<view class="action">
						<button class="cu-btn bg-green margin-left" @tap="successTipHide">确定</button>
					</view>
				</view>
			</view>
		</view> -->
		<!-- 提示删除图片 -->
		<view :class="'cu-modal ' + (showTip? 'show' : '' )">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content text-black">提示</view>
					<view class="action" @tap="showTipHide">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-xl">您确定删除该处方的图片吗？</view>
				<view class="cu-bar bg-white justify-end">
					<view class="action">
						<button class="cu-btn line-green text-green" @tap="showTipHide">取消</button>
						<button class="cu-btn bg-green margin-left" @tap="deleteImg">确定</button>
					</view>
				</view>
			</view>
		</view>
		<view class="cu-modal" :class="modalName=='Modal'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">推荐处方</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="flex justify-between padding-sm flex-wrap ">
					<view class="bg-white margin-bottom-sm" v-for="(item,index) in recommendData" :key="index">
						<view class="">
							<view class="commodity">
								<img :src="item.picUrls[0]" alt="">
							</view>
							<view class="padding-sm">
								<text>{{item.name}}</text>

							</view>
							<view class="padding-sm flex justify-between">
								<text>价格：<text class="text-red">{{item.salesprice}}</text></text>
								<button class="bg-red cu-btn round sm" @tap="purchase(item)">购买</button>
							</view>

						</view>
					</view>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	const {
		base64src
	} = require("@/utils/base64src.js");
	const app = getApp();
	import __config from '@/config/env';
	import util from '@/utils/util';
	import api from '@/utils/api'


	export default {

		data() {
			return {
				CustomBar: this.CustomBar,
				theme: app.globalData.theme, //全局颜色变量
				loading: false,
				userInfo: null,
				showAddr: true,
				uploaderList: [],
				uploaderListH5: [],

				userAddress: {
					telNum: '',
					id: '',
					provinceName: '',
					cityName: '',
					countyName: '',
					address: '',
					detailInfo: ''
				},
				buyerCount: 0,
				//处方付数
				buyerIsdj: 1,
				//是否代煎标志
				tjtype: '', //是否颗粒剂
				djFlag: true,
				//代煎标志
				buyerIsjg: 0,
				//是否加工
				transType: 2,
				//取货方式
				buyerName: null,
				//购买人姓名
				memo: "",
				//备注
				isInvoice: 0,
				//是否开票
				isInvoiceFlag: false,
				//是否开票标志
				title: "",
				// 发票抬头
				identcode: '',
				//税号
				titleActive: false,
				isClause: false,
				shareShow: '',
				goodsList: [],
				pflag: true,
				custServiceFlag: false,
				showTip: false,
				imgIndex: null,
				//要删除的图片下标
				successTip: false,
				distributionList: [{
						name: '自取',
						expressId: 0
					},
					{
						name: '快递',
						expressId: 2
					}
				],
				showInvoice: false,
				posterUrl: "",
				posterShow: false,
				posterConfig: "",
				invoiceData: {}, //发票信息
				invoiceFlag: false,
				adddressList: ["白塔寺药店二楼饮片组（北京市西城区阜内大街165号)", "白塔寺琪卉堂药店（北京市西城区宣武门内大街181号一层）"],
				genderList: ["男", "女"],
				gender: "",
				isPrescription: null,
				isOpen: null,
				modalName: null,
				recommendData: [],
				purchaseSpu: {},
				displayShow: false,
			};
		},
		props: {},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			var that = this
			app.initPage().then(res => {
				that.userInfoGet();
                that.upload();
				if (options.referee) {
					let params = {
						referee: referee,
						wxUseropenId: uni.getStorageSync('user_info').wxUseropenId
					}
					that.bindSpread(params);
				}
				that.getDefaultAddress();
			})
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {

		},
		onShareAppMessage: function() {
			let title = '金象电商平台';
			let path = 'pages_grid/pages/prescription-upload/photo-upload/index?referee=' + uni.getStorageSync(
				'user_info').refereeId || '';
			console.log(`path`, path)
			return {
				title: title,
				path: path,
				success: function(res) {
					if (res.errMsg == 'shareAppMessage:ok') {
						console.log(res.errMsg);
					}
				},
				fail: function(res) { // 转发失败
				}
			};
		},
		methods: {

			getUserzeropay() { //查看客户是否为0元付款\
				let id = this.userInfo.id
				api.getUserzeropay(id).then(res => {
					console.log(res);
					if (res.data) {
						this.isPrescription = res.data.isPrescription;
						this.isOpen = res.data.isOpen;
						this.transType = 0
					}
				});
			},
			genderChange(e) {
				let index = Number(e.detail.value)
				this.gender = this.genderList[index]
				console.log(this.gender)
			},
			setInvoice(obj, obk) {
				if (obj == 0) {
					this.invoiceData = obk;
					this.invoiceFlag = true
				} else {
					this.invoiceFlag = false
				}
			},
			bindSpread(params) {
				//绑定分用人
				console.log(`处方上传推荐人绑定参数`, params);
				api.bindSpread(params).then(res => {
					console.log(`处方上传推荐人绑定接口返回参数`, res.data);
				});
			},
			getDistribution(id) {
				//查询配送方式
				api.getDistribution(id).then(res => {
					console.log(res);
					let distributionList = res.data;
					if (distributionList.length > 0) {
						let transType = distributionList[1].expressId;
						this.distributionList = distributionList
						this.transType = transType
					}
				});
			},
			hideModal() {
				this.custServiceFlag = false
				this.modalName = null
				// this.setData({
				// 	custServiceFlag: false
				// });
			},
			showPres() {
				if (app.globalData.wxUser.tabBarFlag == 0) {
					this.custServiceFlag = true
					// this.setData({
					// 	custServiceFlag: true
					// });
				} else {
					this.custServiceFlag = false
					// this.setData({
					// 	custServiceFlag: false
					// });
				}
			},
			wxUserGet() {
				api.wxUserGet().then(res => {
					this.userInfo = res.data
					console.log(res)
					// this.setData({
					// 	userInfo: res.data
					// });
				});
			},

			setUserAddress(e) {
				console.log(`123`, e)
				this.userAddress = e
			},
			//获取商城用户信息
			userInfoGet() {
				api.userInfoGet().then(res => {
					this.userInfo = res.data;
					this.getUserzeropay(); //查看是否为0元付款客户
				});
			},
			selectClause() {
				if (this.isClause == true) {
					this.isClause = false
					this.titleActive = false
					// this.setData({
					// 	isClause: false,
					// 	titleActive: false
					// });
				} else {
					this.isClause = true
					this.titleActive = true
					// this.setData({
					// 	isClause: true,
					// 	titleActive: true
					// });
				}
			},
			setBuyname(e) {
				this.buyerName = e.detail.value
			},
			// isklj(e) {
			// 	//是否颗粒剂
			// 	let flag = e.detail.value;
			// 	this.tjtype = flag ? 1 : ''
			// },
			isdj(e) {
				//是否代煎
				let flag = e.detail.value;
				if (flag) {
					this.djFlag = true
					this.buyerIsdj = 1
				} else {
					this.djFlag = false
					this.buyerIsdj = 0
				}
			},

			isjg(e) {
				//是否加工
				this.buyerIsjg = e.detail.value
			},

			selectNum(e) {
				//选择处方付数
				this.buyerCount = e.detail.value
			},

			btnClick(item) {
				this.transType = item.expressId
			},

			selectInvoice(e) {
				//是否开发票
				let flag = e.detail.value;
				if (flag) {
					this.isInvoiceFlag = true
					this.isInvoice = 1
				} else {
					this.isInvoiceFlag = false
					this.isInvoice = 0
				}
			},


			memoInput(e) {
				//备注
				this.memo = e.detail.value
			},

			upload() {
				//选择推荐处方
				this.modalName = 'Modal'
				api.goodspackage().then(res => {
					console.log(res)
					this.recommendData = res.data.records
				})

			},
			purchase(item) {

				this.purchaseSpu = item;

				this.displayShow = true;
				this.modalName = null
			},

			showTipOpen(index) {
				this.showTip = true
				// this.imgIndex = index
			},
			showTipHide() {
				this.showTip = false
			},
			deleteImg(e) {

				this.displayShow = false;
				this.purchaseSpu = {}
				this.showTip = false
			},
			wxgetSnowflake() {
				app.getUserInfo()
				//图片上传之前需要id
				var that = this;
					if (!this.buyerName) {
						uni.showToast({
							title: '请输入用药人姓名',
							icon: 'none',
							duration: 1500
						});
					} else if (!this.gender) {
						uni.showToast({
							title: '请选择性别',
							icon: 'none',
							duration: 1500
						});
					} else if (!/^\d{1,}$/.test(this.buyerCount)) {
						uni.showToast({
							title: '处方付数请输入纯数字',
							icon: 'none',
							duration: 1500
						});
					} else if (this.buyerCount < 1) {
						uni.showToast({
							title: '请选择您的处方付数',
							icon: 'none',
							duration: 1500
						});
					} else if (this.buyerCount > 10000) {
						uni.showToast({
							title: '付数超出限制（10000付）',
							icon: 'none',
							duration: 1500
						});
					}else if (this.transType != 0 && !this.userAddress.id) {
						uni.showToast({
							title: '请选择您的邮寄地址',
							icon: 'none',
							duration: 1500
						});
					} else {
						that.loading = true
						api.wxgetSnowflake().then(res => {
							if (res.code == 0) {
								that.imageCode = res.data
								uni.requestSubscribeMessage({
									tmplIds: ['6nJMWMlFxfiWZbwTrHmRbXHRGzHv0n3ozU48Hd9-2Mo'],
									// 此处可填写多个模板 ID，但低版本微信不兼容只能授权一个
									success(res) {
										that.submitPres();
										console.log('已授权接收订阅消息');
									}
								});
							} else {
								that.loading = false
							}
						}).catch(() => {
							that.loading = false
						});
					}
			},
			submitPres() {
				// return
				//图片和信息一起提交
				let userInfo = this.userInfo;
				let phone = null;
				let buyerName = this.buyerName;
				let isInvoice = 0
				let title = null
				let identcode = null

				if (this.invoiceData.length > 0) {
					isInvoice = 1
					title = this.invoiceData[0].rise
					identcode = this.invoiceData[0].tax
				}
				if (this.transType == 0) {
					this.userAddress.telNum = null
					this.userAddress.id = null
					this.userAddress.provinceName = null
					this.userAddress.cityName = null
					this.userAddress.countyName = null
					this.userAddress.detailInfo = null
					phone = userInfo.phone;
				} else {
					phone = this.userAddress.telNum;
				}
				var that = this;
				var postData = {
					goodsPackage: this.purchaseSpu,
					// appType: 'MA',
					comefrom: 3,
					// 邮费
					// transFee:'10', 
					buyerName: buyerName,
					//购买人姓名
					buyerPhone: phone,
					buyerGender: userInfo.sex,
					//购买人性别(1:男,2:女)
					gender: this.gender === "男" ? 1 : 2,
					buyerBirthday: userInfo.birthday,
					//购买人年龄
					customerId: userInfo.mallUserId,
					openId: userInfo.phone,
					addressId: this.userAddress.id,
					//地址id
					province: this.userAddress.provinceName,

					//省
					city: this.userAddress.cityName,
					//市
					county: this.userAddress.countyName,
					//区
					buyerAddress: this.userAddress.detailInfo,
					//地址  
					buyerCount: this.buyerCount,
					//数量
					buyerIsdj: this.buyerIsdj,
					
					//是否代煎(0:否,1:是)
					buyerIsjg: this.buyerIsjg,
					//是否加工(0:否,1:是)
					logisticsType: this.transType,
					// 取药方式0自取
					buyerMemo: this.memo,
					//备注
					isInvoice: isInvoice,
					// 是否开票
					title: title,
					// 发票抬头
					identcode: identcode,
					// 税号
					id: this.imageCode, //上传图片携带的ID
					organId: '1', //公司ID
					presFrom: 0, //上传方式

				};
				console.log('确认提交参数==============', postData);
				// return
				let url = '/mallapi/api/ma/prescriptions/recommendPresUpLoad'
				let _url = __config.basePath + url;
				uni.request({
					url: _url,
					data: postData,
					header: {
						'app-id': 'wxce3d675f6e1728e4',
						'client-type': 'MA',
						'third-session': uni.getStorageSync('third_session')
					},
					method: 'POST',
					dataType: 'json',
					responseType: 'text',
					success: res => {
						that.setData = false
						if (res.data.code == 1) {
							uni.hideLoading();
							uni.showModal({
								title: '提示',
								content: res.data.msg
							});
						} else if (res.data.code == 60001) {
							uni.showToast({
								title: '登录超时，请重新登录',
								icon: 'none',
								duration: 2000
							});
						} else {

							that.uploaderList = []
							uni.hideLoading();
							uni.redirectTo({
								url: '/pages/order/order-detail/index?id=' + res.data.data
							})
						}
					},
					fail: res => {},
					complete: res => { // console.log(res)
						that.loading = false
					}
				});
			},

			getDefaultAddress() {
				//获取默认收货地址
				api.getDefaultAddress().then(res => {
					let data = res.data;
					if (data) {
						this.userAddress = data
					}
				});
			},

			jumpToAddressList() {
				//跳转到收货地址页面
				uni.navigateTo({
					url: '/pages/user/user-address/list/index?select=true'
				});
			},

			successTipHide() {
				//处方上传成功后的提示
				this.successTip = false
				this.shareShowFun();
			},
			shareShowFun() {
				this.shareShow = show
			},
		}
	};
</script>
<style>
	@import "./index.css";
</style>
